<?php

declare(strict_types=1);
namespace App\Controller\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\AbstractController;
use Hyperf\Utils\ApplicationContext;
use App\Service\AliyunService\QueryIpAddressService;
use App\Service\AliyunService\QueryLatLngtoAddressService;

/**
 * @Controller(prefix="/QueryIp")
 * ip查询中心
 */
class QueryIpController extends AbstractController
{
    /**
     * ip查询中心
     * @RequestMapping(path="index", methods="GET")
     * @return string[]
     */
    public function queryRegionList(RequestInterface $request) 
    {
        return $this->getRealIp();
    }
    
    /**
     * 通过ip地址查询归属（省市区）
     * @RequestMapping(path="queryIpAddress", methods="GET")
     * @return string[]
     */
    public function queryIpAddress(RequestInterface $request,QueryIpAddressService $service)
    {
        return $service->QueryAddressByIp((string)$request->input('ip'));
    }
    
    /**
     * 通过经纬度查询归属（省市区）
     * @RequestMapping(path="queryLatlngtoAddress", methods="GET")
     * @return string[]
     */
    public function queryLatlngtoAddress(RequestInterface $request,QueryLatLngtoAddressService $service)
    {
        return $service->QueryAddressByLatLngto(
            (string)$request->input('lat'),
            (string)$request->input('lng')
            );
    }
    
    /**
     * 获取客户端真实ip地址
     */
    public function getRealIp()
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $headers = $request->getHeaders();
    
        if(isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) {
            return $headers['x-forwarded-for'][0];
        } elseif (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) {
            return $headers['x-real-ip'][0];
        }
    
        $serverParams = $request->getServerParams();
        return $serverParams['remote_addr'] ?? '';
    }
}
